//app.js
App({
  onLaunch: function () {
    
  },

  globalData: {
    _bluetoothState: 'PENDING',
    _writeState: 'ERROR'
  },

  watch: function(method, key){
    var obj = this.globalData;
    Object.defineProperty(obj, key, {
      configurable: true,
      enumerable: true,
      set: function (value) {
        this['_' + key] = value;
        method(value);
      },
      get:function(){
      // 可以在这里打印一些东西，然后在其他界面调用getApp().globalData.name的时候，这里就会执行。
        return this['_' + key]
      }
    });
  }

})




/*****************************************************************/

function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}

function str2ab(str) {
  var buf = new ArrayBuffer(str.length);
  var bufView = new Uint8Array(buf);
  for (var i = 0, strLen = str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}
var device_id;
var service_id;
var chr_id;

function my_connect() {
  wx.onBLEConnectionStateChange(function (res) {
    // 该方法回调中可以用于处理连接意外断开等异常情况
    console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
    if (res.connected == false){
      wx.createBLEConnection({
        deviceId: device_id,
        success(res) {
          console.log(res)
        }
      })
    }

    if (res.connected) {
      wx.showToast({
        title: '连接成功',
        icon: 'success',
        duration: 2000
      })
      getApp().globalData.bluetoothState = 'SUCCESS'
      wx.getBLEDeviceServices({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: device_id,
        success(res) {
          var x;
          //console.log('device services:', res.services)
          for (x in res.services) {
            //console.log("uuid" + res.services[x].uuid)
            if (res.services[x].uuid == "0000FFFF-0000-1000-8000-00805F9B34FB") {
              console.log("OK")
              service_id = res.services[x].uuid;

              wx.getBLEDeviceCharacteristics({
                // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
                deviceId: device_id,
                // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
                serviceId: service_id,
                success(res) {
                  //console.log('device getBLEDeviceCharacteristics:', res.characteristics)
                  var y;
                  for (y in res.characteristics) {
                    if (res.characteristics[y].uuid == "0000FF01-0000-1000-8000-00805F9B34FB") {
                      chr_id = res.characteristics[y].uuid;

                    }

                  }


                }
              })
            }
          }
        }
      })
    }

  })

}



function my_write(msg) {
  wx.showLoading({
    title: '写入中',
    mask: true
  });
  let buffer = new ArrayBuffer(20);
  buffer = str2ab(msg);
  console.log(buffer)
  wx.writeBLECharacteristicValue({
    // 这里的 deviceId 需要在 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
    deviceId: device_id,
    // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
    serviceId: service_id,
    // 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
    characteristicId: chr_id,
    // 这里的value是ArrayBuffer类型

    value: buffer,
    success(res) {
      wx.hideLoading()
      getApp().globalData.writeState = 'SUCCESS'
      wx.showToast({
        title: '写入成功',
        icon: 'success',
        duration: 2000
      })
    },
    error(res) {
      wx.hideLoading()
      getApp().globalData.writeState = 'ERROR'
      wx.showToast({
        title: '写入失败',
        icon: 'none',
        duration: 2000
      })
    }
  })
}


wx.openBluetoothAdapter({
  success: function (res) {
    console.log("初始化蓝牙适配器成功：" + res)
    wx.getStorage({
      key: 'dev_id',
      success: function (res) {
        device_id = res.data
      }
    })
    console.log("device_id_old "+ device_id);
   if (device_id != undefined)
    {
      wx.createBLEConnection({
        deviceId: device_id,
        success(res) {
          console.log(res)
        }
      })
      return;
    }
    wx.onBluetoothDeviceFound(function (res) {
      var devices = res.devices;
      //console.log('new device list has founded')
      //console.dir(devices)
      //console.log(devices[0].localName)
      if (devices[0].localName == "bk-37cd") {
        console.log('bk-37cdhas founded,now Connect...')

        device_id = devices[0].deviceId;
        console.log("device_id "+device_id);
        wx.setStorageSync('dev_id',device_id)
        my_connect();
        wx.stopBluetoothDevicesDiscovery()
        wx.createBLEConnection({
          deviceId: device_id,
          success(res) {
            console.log(res)
          }
        })

      }
    })


    wx.startBluetoothDevicesDiscovery({
      success: function () {
        console.log("搜索蓝牙：" + res)
      }

    })
  }

})



module.exports = {

  my_write: my_write,
}